﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Identity.Infrastructure;
using Identity.Models;
using Identity.ViewModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Threading.Tasks;

namespace MVC.Controllers
{
    //todo:以后尝试连控制器也移到Identity程序集
    public class AdminController : Controller
    {
        private AppUserManager UserManager
        {
            get { return HttpContext.GetOwinContext().GetUserManager<AppUserManager>(); }
        }
        
        // GET: Admin
        public ActionResult Index()
        {
            return View(UserManager.Users);
        }

        // GET: Admin/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Admin/Create
        [HttpPost]
        public async Task<ActionResult> Create(CreateUserVm model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    AppUser user = new AppUser()
                    {
                        UserName = model.Name,
                        Email = model.Email,
                    };
                    IdentityResult result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }  
            }
            catch
            {
                //
            }
            return View();
        }

        // GET: Admin/Edit/5
        public async Task<ActionResult> Edit(string id)
        {
            var user = await UserManager.FindByIdAsync(id);
            if (user != null)
            {
                return View(new EditUserVm()
                {
                    Id = user.Id,
                    Email = user.Email,
                    Name = user.UserName,
                    Password = ""
                });
            }
            return RedirectToAction("Index");
        }

        // POST: Admin/Edit/5
        [HttpPost]
        public async Task<ActionResult> Edit(EditUserVm model)
        {
            try
            {
                // TODO: Add update logic here
                var user = await UserManager.FindByIdAsync(model.Id);
                if (user != null)
                {
                    user.Email = model.Email;
                    user.UserName = model.Name;
                    IdentityResult validUser = await UserManager.UserValidator.ValidateAsync(user);
                    if (!validUser.Succeeded)
                    {
                        AddErrorsFromResult(validUser);
                    }
                    IdentityResult validPass = await UserManager.PasswordValidator.ValidateAsync(model.Password);
                    if (!validPass.Succeeded)
                    {
                        AddErrorsFromResult(validPass);
                    }
                    else
                    {
                        user.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password);
                    }

                    if ((validUser.Succeeded && validPass.Succeeded))
                    {
                        IdentityResult result = await UserManager.UpdateAsync(user);
                        if (result.Succeeded)
                        {
                            return RedirectToAction("Index");
                        }
                        else
                        {
                            AddErrorsFromResult(result);
                        }
                    } 
                }
            }
            catch
            {
                
            }
            return View(model);
        }

        // GET: Admin/Delete/5
        public ActionResult Delete(string id)
        {
            var user = UserManager.FindById(id);
            ViewBag.UserName = user.UserName;
            return View();
        }

        // POST: Admin/Delete/5
        [HttpPost,ActionName("Delete")]
        public async Task<ActionResult> DeleteConfirmed(string id)
        {
            try
            {
                //todo:避免进行数据库查询操作，直接赋值新建AppUser
                var user =await UserManager.FindByIdAsync(id);
                IdentityResult result = await UserManager.DeleteAsync(user);
                if (result.Succeeded)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return View("Error", result.Errors);
                }
            }
            catch
            {
                //
            }
            return View();
        }

        private void AddErrorsFromResult(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("",error);
            }
        }
    }
}
